<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理静态页面 -->
      <div class="hear-button-box">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 列表位置 -->
      <el-table :data="list">
        <el-table-column prop="name" label="角色" align="center" width="250">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="state" label="启用" align="center" width="200">
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述" align="center">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="btnEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>

            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" style="margin-left:15px" @onConfirm="deldateRole(row)">
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-row type="flex" align="middle" justify="end" style=" hight:80px; margin-top: 20px;">
        <el-pagination
          size="20"
          layout=" prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 弹层组件 -->
    <el-dialog
      title="新增角色"
      :visible.sync="showDialog"
      width="30%"
      @close="btnCancel"
    >
      <el-form ref="form" label-width="100px" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width: 300px" size="mini" />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" style="width: 300px" :rows="3" size="mini" />
        </el-form-item>

        <el-form-item label="启用">
          <el-switch
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="start">
            <el-button size="mini" type="primary" @click="btnOK">确定</el-button>
            <el-button size="mini" @click="btnCancel">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 点击编辑 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <el-tree
        ref="treeRef"
        check-strictly
        :props="permissionProps"
        :data="permissionData"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="btnPermissionOk">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

  </div>
</template>
<script>
import { getRoleListAPI, addRole, getRoleDetail, assignPerm } from '@/api/role'
import { updateRole, deldateRole } from '@/api/user'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 当前页数
        pagesize: 5, // 一页多少条,
        total: 0 // 一共多少条数据
      },
      showDialog: false, // 弹窗
      showPermissionDialog: false, // 点击编辑弹窗
      permissionData: [], // 编辑弹窗数据
      permIds: [], // 回显树形权限数据
      currentRoleId: null, // 权限id
      permissionProps: { // 树形数据
        label: 'name'
      },
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: { // 校验规则
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleListAPI(this.pageParams)
      this.list = res.rows
      this.list.forEach(item => {
        // item.isEdit = false  错误用法添加的数据没有响应式
        // this.$set(目标对象, 属性名称, 属性值) 这样添加的属性才是有响应式的
        this.$set(item, 'isEdit', false)
        // 备份当前行显示的数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = res.total
    },
    changePage(val) {
      this.pageParams.page = val
      this.getRoleList()
    },
    btnOK() { // 点击确定
      this.$refs.form.validate(async val => {
        if (val) {
          await addRole(this.roleForm)
          try {
            this.$message.success('添加成功')
            this.getRoleList()
            this.btnCancel()
          } catch (error) {
            console.log(error)
          }
        }
      }
      )
    },
    btnCancel() { // 点击取消
      this.$refs.form.resetFields()
      this.showDialog = false
    },
    btnEditRow(row) { // 点击编辑
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async btnEditOk(row) { // 编辑点击确定
      if (row.editRow.name && row.editRow.description) { // 必须都有值才能提交
        await updateRole({ ...row.editRow, id: row.id })
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
        this.$message.success('数据更新成功')
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async deldateRole(row) { // 点击确定删除删除
      await deldateRole(row.id)
      this.$message.success('删除结果成功')
      if (this.list.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    async btnPermission(row) { // 点击编辑
      this.currentRoleId = row.id
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true
      const { permIds } = await getRoleDetail(row.id)
      this.permIds = permIds
    },
    async btnPermissionOk() { // 编辑点击确定
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
<style>
.hear-button-box {
  padding: 5px;
}

</style>
